from typing import Optional, List
from ninja import FilterSchema, Field, ModelSchema
from django.db.models import Q

from models.models import WaterDropletsRecord, WaterDropletsTask, User


class WaterDropletsRecordFilterSchema(FilterSchema):
    """用户订单筛选"""
    task_name: Optional[str] = Field(default=None, description="任务名称", q="task__task_name__icontains")
    user: Optional[str] = Field(default=None, description="操作人",
                                q=["user__nickname__contains", "user__openid__contains",
                                   "user__phone_number__contains"])
    op_type: Optional[int] = Field(default=None, description="类型", choices=[(1, "获取"), (2, "消耗")])
    op_time: Optional[dict] = None

    def filter_time(self, value: dict):
        if not value:
            return Q()
        if value.get('start') and not value.get('end'):
            return Q(op_time__gt=value.get('start'))
        if not value.get('start') and value.get('end'):
            return Q(op_time__lt=value.get('end'))
        if value.get('start') and value.get('end'):
            return Q(op_time__gt=value.get('start'), op_time__lt=value.get('end'))
        return Q()


class WaterDropletsTaskModelSchema(ModelSchema):
    """用户水滴任务返回"""

    class Config:
        model = WaterDropletsTask
        model_fields = ["task_name"]


class WaterDropletsRecordUserSchema(ModelSchema):
    """水滴记录用户"""

    class Config:
        model = User
        model_fields = ["nickname", "openid"]


class WaterDropletsRecordResponseSchema(ModelSchema):
    """用户水滴记录返回"""
    user: WaterDropletsRecordUserSchema = None
    task: WaterDropletsTaskModelSchema = None

    class Config:
        model = WaterDropletsRecord
        model_fields = "__all__"
